package com.ruoyi.system.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.common.SysConstant;
import com.ruoyi.system.config.CaptchaProperties;
import com.ruoyi.system.form.LoginBody;
import com.ruoyi.system.service.SysLoginService;
import com.ruoyi.system.service.ValidateCodeService;

import lombok.extern.slf4j.Slf4j;
import start.spring.basic.log.ServiceLog;
import start.spring.basic.ry.core.utils.StringUtils;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@Slf4j
@RequestMapping("/auth")
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;
    
    @Autowired
    private ValidateCodeService validateCodeService;
    
    @Autowired
    private CaptchaProperties captchaProperties;
    
    @GetMapping("/get/code")
    public AjaxResult getValidateCode() {
        // 获取验证码
    	try {
			AjaxResult ajax = validateCodeService.createCaptcha();
			return ajax;
		} catch (CaptchaException | IOException e) {
			log.error("", e);
			return AjaxResult.error(e.getMessage());
		} catch (Exception e) {
			log.error("", e);
			return AjaxResult.error("生成验证码失败");
		} 
    }

    @ServiceLog(businessType = "用户登录", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
    	try {
    		//校验验证码
        	this.checkCode(form.getCode(),form.getUuid());
		} catch (CaptchaException e) {
			log.error("", e);
			return R.fail(e.getMessage());
		} catch (Exception e) {
			log.error("", e);
			return R.fail("验证码验证失败！");
		} 
    	
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @ServiceLog(businessType = "退出登录", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @ServiceLog(businessType = "用户注册", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @PostMapping("register")
    public R<?> register(HttpServletRequest request, @RequestBody LoginBody registerBody) {
    	try {
    		//校验验证码
        	this.checkCode(registerBody.getCode(),registerBody.getUuid());
		} catch (CaptchaException e) {
			log.error("", e);
			return R.fail(e.getMessage());
		} catch (Exception e) {
			log.error("", e);
			return R.fail("验证码验证失败！");
		} 
    	
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
    
    /**
     * 校验验证码
     *	
     * @since           1.0
     */
    private void checkCode(String code, String uuid) {
    	//开启了验证码
    	if(captchaProperties.getEnabled()) {
    		validateCodeService.checkCaptcha(code, uuid);
    	}
    }
}
